package net.chrisrichardson.ormunit.hibernate;

import java.util.HashSet;
import java.util.Set;

/**
 * Utility methods for manipulating sets of dotted property names
 * @author cer
 *
 */
public class PathUtil {

	/**
	 * Return paths starting with the specified prefix with the prefix removed
	 * @param prefix
	 * @param propertyNames
	 * @return
	 */
	public static Set<String> getPathsStartingWith(String prefix, Set<String> propertyNames) {
		String prefixToChop = prefix + ".";
		Set<String> result = new HashSet<String>();
		for (String fieldName : propertyNames) {
			if (fieldName.startsWith(prefixToChop))
				result.add(fieldName.substring(prefixToChop.length()));
		}
		return result;
	}

	/**
	 * Return the properties that don't have sub-properties
	 * @param propertyNames
	 * @return
	 */
	public static Set<String> getPropertiesWithNonSubProps(Set<String> propertyNames) {
		Set<String> result = new HashSet<String>();
		for (String field : propertyNames) {
			int n = field.indexOf('.');
			if (n == -1)
				result.add(field);
		}
		return result;
	}

	/**
	 * Return the names of the top-level properties
	 * @param propertyNames
	 * @return
	 */
	public static Set<String> getRoots(Set<String> propertyNames) {
		Set<String> result = new HashSet<String>();
		for (String field : propertyNames) {
			int n = field.indexOf('.');
			if (n == -1)
				result.add(field);
			else
				result.add(field.substring(0, n));
	
		}
		return result;
	}

}
